/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.Course;
import com.jmooc.entity.User;
import com.jmooc.entity.UserCertification;
import com.jmooc.service.UserCertificationService;
import com.jmooc.service.UserService;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "CertificationServlet", urlPatterns = {"/certification/*"} )
public class CertificationServlet extends HttpServlet {

    @EJB
    private UserService userService;
    
    @EJB
    private UserCertificationService userCertificationService;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Long certificationId = Long.valueOf(request.getPathInfo().substring(1));
        
        Course course = null;
        UserCertification certification = null;
        
        try {
            certification = userCertificationService.getById(certificationId);
            course = certification.getCourse();

            User user = userService.getById((Long)session.getAttribute("userId"));

            if (!certification.getUser().equals(user))
                throw new Exception();
            
            request.setAttribute("user", user);
            request.setAttribute("course", course);
            request.setAttribute("certification", certification);
            
            Date now = new Date(); 
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 

            request.setAttribute("now", dateFormat.format(now));
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("message", "Erreur dans la certification");
        }
        
        request.getRequestDispatcher("/jsp/certification.jsp").forward(request, response);
    }

}
